using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Rensoft.CRM.Client.AccountsAPI;
using Rensoft.CRM.Client.Properties;
using Rensoft.CRM.Client.Editors;

namespace Rensoft.CRM.Client.ItemViews
{
    public partial class CreditView : Rensoft.CRM.Client.ItemViews.BaseView
    {
        protected List<Credit> creditList;

        public Credit[] CreditArray
        {
            get { return creditList.ToArray(); }
            set { creditList = new List<Credit>(value); }
        }

        protected CreditView()
        {
            InitializeComponent();
        }

        public override Image NewButtonImage
        {
            get { return Resources.Invoices; }
        }

        public CreditView(Program program)
            : base(program)
        {
            InitializeComponent();
        }

        protected override void PerformLoad()
        {
            base.PerformLoad();
            AccountsService service = AccountsService.CreateInstance();
            creditList = new List<Credit>(service.CreditFetchAll());
        }

        protected override void LoadComplete(RunWorkerCompletedEventArgs e)
        {
            if (creditList != null)
            {
                creditList.Sort(new Comparison<Credit>(creditSorter));

                ItemsListView.VirtualListSize = CreditArray.Length;
                ItemsListView.VirtualMode = true;
                UpdateItemCount(CreditArray.Length);
            }
            else
            {
                // No items downloaded, so count is 0.
                UpdateItemCount(0);
            }

            base.LoadComplete(e);
        }

        private int creditSorter(Credit left, Credit right)
        {
            if (left.Date.Ticks > right.Date.Ticks)
            {
                return (ItemsListView.Sorting == SortOrder.Descending) ? -1 : 1;
            }

            if (left.Date.Ticks < right.Date.Ticks)
            {
                return (ItemsListView.Sorting == SortOrder.Descending) ? 1 : -1;
            }

            return 0;
        }

        protected override void OnRetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            Credit credit = (Credit)CreditArray[e.ItemIndex];

            e.Item = new ListViewItem(
                new string[] {
                    credit.AccountCode,
                    credit.ValueAmount.ToString("N"),
                    credit.Date.ToShortDateString(),
                    credit.Reference});

            e.Item.Tag = credit;

            base.OnRetrieveVirtualItem(sender, e);
        }

        internal override Rensoft.CRM.Client.Editors.BaseEditor GetEditor()
        {
            return new CreditEditor(Program);
        }
    }
}

